var upTasks = [];
var taskStartFlag = false;
var taskNum = 0;
var progressInterval = null;
var showButtonDownMousePosition = null;
var upSpeed = {
    //上传完成的文件
    finishFile:0,
    //总共要上传的文件
    totalFile:0,
    //之前上传的文件字节
    prevUpSize:0,
    //正在上传的文件字节
    nowUpSize:0,
    //所有文件大小
    totalFileSize:0,
    //已用时间
    time:0,
}
taskHtmlInit()
function taskHtmlInit(){
    var taskList = document.getElementsByClassName('task-list')[0]
    taskList.className = taskList.className + " default-fileup-style"
    var taskListHeaderHtml = '<div class="task-list-header">\n' +
        '        <span><span class="up-speed">上传列表</span></span>\n' +
        '        <div class="hide-task">—</div>\n' +
        '    </div>\n' +
        '\n'
    var noTaskHtml = '<p class="no-task">无任务</p>'
    var showButton = '<div class="show-button" onselectstart="return false;" unselectable="on">文<br/>件<br/>上<br/>传</div>'
    taskList.insertAdjacentHTML('beforeend',taskListHeaderHtml)
    taskList.insertAdjacentHTML('beforeend',noTaskHtml)
    taskList.insertAdjacentHTML('afterend',showButton)

    document.getElementsByClassName('show-button')[0].onmousedown=mousedownShowButton
    document.getElementsByClassName('show-button')[0].onmouseup=function (ev){
        document.onmousemove = null;
        var nowMousePosition = mousePosition(ev)
        if (nowMousePosition.x == showButtonDownMousePosition.x && nowMousePosition.y == showButtonDownMousePosition.y){
            showTaskList();
        }
    }

    document.getElementsByClassName('hide-task')[0].onclick=function (){
        document.getElementsByClassName('task-list')[0].style.display = "none"
        document.getElementsByClassName('show-button')[0].style.display = "block"
    }
}

function showTaskList(){

    var taskList = document.getElementsByClassName('task-list')[0]
    var showButton = document.getElementsByClassName('show-button')[0];
    var style = window.getComputedStyle(showButton)
    var taskListStyle = window.getComputedStyle(taskList)
    var bodyWidth = document.documentElement.clientWidth
    var bodyHeight =document.documentElement.clientHeight
    var buttonTop = parseInt(style.top)
    var buttonLeft = parseInt(style.left)
    if (buttonLeft>bodyWidth/2){
        taskList.style.left = buttonLeft-parseInt(taskListStyle.width)+parseInt(style.width)+"px";
    }else{
        taskList.style.left = style.left;
    }
    if (buttonTop>bodyHeight/2){
        taskList.style.top = buttonTop-parseInt(taskListStyle.height)+parseInt(style.height)+"px";
    }else{
        taskList.style.top = style.top;
    }
    showButton.style.display = "none"
    taskList.style.display = "block"
}

function progress(val){
    if (isNaN(parseInt(val)))return;
    var bar =document.getElementsByClassName('bar')[0]
    var barBorder = document.getElementsByClassName('bar-border')[0]
    var progressText = document.getElementsByClassName('progress-text')[0]
    var borderWidth = parseInt(window.getComputedStyle(barBorder).width)
    var progress = parseInt(val);
    bar.style.width = borderWidth/100*progress+"px";
    progressText.innerText = val;
    var totalProgress = ((upSpeed.nowUpSize+upSpeed.prevUpSize)/upSpeed.totalFileSize*100).toFixed(2);
    var totalUpSize = upSpeed.nowUpSize+upSpeed.prevUpSize;

    // nowSize是请求的整体的大小，包括协议的内容，所以在小于或等于0时视为已经上传完毕
    var totalTime = ((upSpeed.totalFileSize-totalUpSize)/(totalUpSize/(upSpeed.time/1000))).toFixed(0);


    var speedText = upSpeed.finishFile+"/"+upSpeed.totalFile+"，"+totalProgress+"%"+"，"+(totalTime<=0?'completed!':totalTime+"s");
    document.getElementsByClassName('up-speed')[0].innerHTML = speedText;
}

function mousePosition(ev){
    if(ev.pageX || ev.pageY){
        return {x:ev.pageX, y:ev.pageY};
    }
    return {
        x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y:ev.clientY + document.body.scrollTop - document.body.clientTop
    };
}

function mousedownShowButton(ev){
    var obj = this
    var sourceTop = parseInt(window.getComputedStyle(obj).top)
    var sourceLeft = parseInt(window.getComputedStyle(obj).left)
    showButtonDownMousePosition = mousePosition(ev);
    document.onmousemove = function (ev){
        var mousePos = mousePosition(ev);
        obj.style.top = sourceTop + mousePos.y - showButtonDownMousePosition.y +"px";
        obj.style.left =sourceLeft+ mousePos.x- showButtonDownMousePosition.x +"px";
    };
}

/**
 * 添加任务
 * @param task:{
 *     upData:上传数据,
 *     url:请求地址,
 *     method:请求方法,
 *     headers:请求头,
 *     performAfter:回调
 *
 * }
 */
function addTask(task){
    task.progress = '等待中'
    if(upTasks.length == taskNum){
        upTasks.push(task)
    }else{
        upTasks[taskNum] = task
    }
    taskNum++;
    document.getElementsByClassName('no-task')[0].style.display = 'none'
    addTaskHtml(task)
    upSpeed.totalFile++;
    upSpeed.totalFileSize+= task.upData.file.size
    startTask();
}

function resetUpSpeed(){
    upSpeed = {
        finishFile:0,
        totalFile:0,
        prevUpSize:0,
        nowUpSize:0,
        totalFileSize:0,
        time:0
    }
}

function addTaskHtml(task){
    var taskHtml = "<div class=\"task\">\n" +
        "            <div class=\"task-header\">\n" +
        "                <label class=\"task-header-text task-name\">"+task.name+"</label>\n" +
        "                <label class=\"task-header-text progress-text\">"+task.progress+"</label>\n" +
        "            </div>\n" +
        "            <div class=\"bar-border\">\n" +
        "                <div class=\"bar\"></div>\n" +
        "            </div>\n" +
        "            <div class=\"task-shade\">\n" +
        "                <lable class=\"task-shade-text\">上传成功</lable>\n" +
        "            </div>\n" +
        "        </div>"
    var taskList = document.getElementsByClassName('task-list')[0]
    taskList.insertAdjacentHTML('beforeend',taskHtml)
}

function performTask(){
    taskNum--;
    upSpeed.prevUpSize += upTasks[0].upData.file.size;
    upSpeed.nowUpSize = 0;
    for (let i = 0; i < taskNum; i++) {
        upTasks[i] = upTasks[i+1];
    }
    var task = document.getElementsByClassName('task')[0]
    var taskShade = document.getElementsByClassName('task-shade')[0]
    taskShade.style.display = "block"
    task.className = task.className+" task-out";
    upSpeed.finishFile++;
    setTimeout(function (){
        task.parentElement.removeChild(task)
    },2000)
}

function startTask(){
    if(!taskStartFlag){
        taskStartFlag = true;
        processTask();
        progressInterval = setInterval(function (){
            var task = upTasks[0]
            if (task != null){
                progress(task.progress);
                upSpeed.time+=50;
            }
        },50)
        showTaskList()
    }
}

function processTask(){
    var fd = new FormData();
    var taskData = upTasks[0]
    for (var key in taskData.upData){
        fd.append(key,taskData.upData[key])
    }
    var xhr =new XMLHttpRequest();// XMLHttpRequest 对象
    xhr.open(taskData.method, taskData.url, true); //put方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
    if (taskData.headers != null){
        for (let headersKey in taskData.headers) {
            xhr.setRequestHeader(headersKey,taskData.headers[headersKey])
        }
    }
    xhr.onerror = function (ev) {
        performTask()
        nextTaskProcess()
    }; //请求失败
    xhr.upload.onprogress = function (ev) {
        var progressRate = (ev.loaded / ev.total) * 100+'';
        taskData.progress = parseInt(progressRate) + "%";
        upSpeed.nowUpSize = ev.loaded
    };
    xhr.upload.onloadstart = function() {
        taskData.progress = '0%'
    };
    xhr.onreadystatechange = function(){

        if(xhr.readyState==4){
            if(taskData.performAfter!=null){
                taskData.performAfter(xhr)
            }
            performTask()
            nextTaskProcess()
        }


    };
    xhr.send(fd);
}
function nextTaskProcess(){
    setTimeout(function (){
        if (taskNum != 0){
            processTask();
        }else{
            taskStartFlag = false;
            window.clearInterval(progressInterval)
            document.getElementsByClassName('no-task')[0].style.display = 'block'
            document.getElementsByClassName('up-speed')[0].innerHTML = '上传列表';
            resetUpSpeed()
        }
    },2000)

}